// WAF检测工具前端JavaScript

// 全局变量
let currentResults = null;
let isDetecting = false;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

function initializeApp() {
    // 绑定表单提交事件
    document.getElementById('wafForm').addEventListener('submit', handleFormSubmit);
    
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

// 处理表单提交
async function handleFormSubmit(e) {
    e.preventDefault();
    
    if (isDetecting) {
        showAlert('检测正在进行中，请稍候...', 'warning');
        return;
    }
    
    const url = document.getElementById('targetUrl').value.trim();
    const payloadsText = document.getElementById('payloads').value.trim();
    
    if (!url) {
        showAlert('请输入目标URL', 'danger');
        return;
    }
    
    if (!payloadsText) {
        showAlert('请输入测试payload', 'danger');
        return;
    }
    
    const payloads = payloadsText.split('\n').filter(p => p.trim());
    
    isDetecting = true;
    showProgress(true);
    
    try {
        const results = await detectWAF(url, payloads);
        currentResults = results;
        displayResults(results);
        displayBypassResults(results);
    } catch (error) {
        showAlert('检测失败: ' + error.message, 'danger');
    } finally {
        isDetecting = false;
        showProgress(false);
    }
}

// 调用后端API进行检测
async function detectWAF(url, payloads) {
    const response = await fetch('/api/detect', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ url, payloads })
    });
    
    if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    return await response.json();
}

// 显示进度
function showProgress(show) {
    const progressCard = document.getElementById('progressCard');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    
    if (show) {
        progressCard.style.display = 'block';
        simulateProgress();
    } else {
        progressCard.style.display = 'none';
    }
}

// 模拟进度条动画
function simulateProgress() {
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    let progress = 0;
    
    const interval = setInterval(() => {
        progress += Math.random() * 15;
        if (progress > 90) progress = 90;
        
        progressBar.style.width = progress + '%';
        progressBar.textContent = Math.round(progress) + '%';
        progressText.textContent = `检测中... ${Math.round(progress)}%`;
        
        if (!isDetecting) {
            clearInterval(interval);
            progressBar.style.width = '100%';
            progressBar.textContent = '100%';
            progressText.textContent = '检测完成';
        }
    }, 500);
}

// 显示WAF检测结果
function displayResults(results) {
    const container = document.getElementById('resultsContainer');
    
    if (results.error) {
        container.innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> ${results.error}
            </div>
        `;
        return;
    }
    
    let html = `
        <div class="row">
            <div class="col-md-6">
                <div class="stats-card">
                    <div class="stats-number">${results.waf_detected ? '是' : '否'}</div>
                    <div class="stats-label">WAF检测</div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="stats-card">
                    <div class="stats-number">${results.waf_type || '未知'}</div>
                    <div class="stats-label">WAF类型</div>
                </div>
            </div>
        </div>
        
        <div class="mt-3">
            <h6><i class="fas fa-clock"></i> 检测时间: ${new Date(results.detection_time).toLocaleString()}</h6>
        </div>
        
        <div class="mt-4">
            <h6><i class="fas fa-list"></i> Payload测试结果</h6>
            <div class="accordion" id="payloadAccordion">
    `;
    
    results.payload_results.forEach((result, index) => {
        if (result.error) {
            html += `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i> ${result.error}
                </div>
            `;
            return;
        }
        
        html += `
            <div class="accordion-item">
                <h2 class="accordion-header">
                    <button class="accordion-button ${index > 0 ? 'collapsed' : ''}" type="button" 
                            data-bs-toggle="collapse" data-bs-target="#payload${index}">
                        <span class="status-indicator ${result.get_test.blocked ? 'danger' : 'success'}"></span>
                        ${result.original_payload.substring(0, 50)}${result.original_payload.length > 50 ? '...' : ''}
                    </button>
                </h2>
                <div id="payload${index}" class="accordion-collapse collapse ${index === 0 ? 'show' : ''}">
                    <div class="accordion-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>GET测试</h6>
                                <table class="table table-sm">
                                    <tr><td>状态码</td><td><span class="badge ${getStatusBadgeClass(result.get_test.status_code)}">${result.get_test.status_code}</span></td></tr>
                                    <tr><td>响应长度</td><td>${result.get_test.response_length} bytes</td></tr>
                                    <tr><td>是否拦截</td><td>${result.get_test.blocked ? '<span class="badge bg-danger">是</span>' : '<span class="badge bg-success">否</span>'}</td></tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <h6>POST测试</h6>
                                <table class="table table-sm">
                                    <tr><td>状态码</td><td><span class="badge ${getStatusBadgeClass(result.post_test.status_code)}">${result.post_test.status_code}</span></td></tr>
                                    <tr><td>响应长度</td><td>${result.post_test.response_length} bytes</td></tr>
                                    <tr><td>是否拦截</td><td>${result.post_test.blocked ? '<span class="badge bg-danger">是</span>' : '<span class="badge bg-success">否</span>'}</td></tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    html += '</div></div>';
    container.innerHTML = html;
}

// 显示绕过测试结果
function displayBypassResults(results) {
    const container = document.getElementById('bypassContainer');
    
    if (!results.bypass_results || results.bypass_results.length === 0) {
        container.innerHTML = '<div class="text-center text-muted">无绕过测试结果</div>';
        return;
    }
    
    // 按payload分组
    const groupedResults = {};
    results.bypass_results.forEach(result => {
        if (result.original_payload) {
            if (!groupedResults[result.original_payload]) {
                groupedResults[result.original_payload] = [];
            }
            groupedResults[result.original_payload].push(result);
        }
    });
    
    let html = '<div class="accordion" id="bypassAccordion">';
    
    Object.entries(groupedResults).forEach(([payload, bypasses], index) => {
        const successfulBypasses = bypasses.filter(b => b.bypassed);
        const successRate = (successfulBypasses.length / bypasses.length * 100).toFixed(1);
        
        html += `
            <div class="accordion-item">
                <h2 class="accordion-header">
                    <button class="accordion-button collapsed" type="button" 
                            data-bs-toggle="collapse" data-bs-target="#bypass${index}">
                        <span class="status-indicator ${successRate > 0 ? 'success' : 'danger'}"></span>
                        ${payload.substring(0, 50)}${payload.length > 50 ? '...' : ''}
                        <span class="badge bg-secondary ms-2">${successRate}% 成功率</span>
                    </button>
                </h2>
                <div id="bypass${index}" class="accordion-collapse collapse">
                    <div class="accordion-body">
                        <div class="table-responsive">
                            <table class="table table-sm table-hover">
                                <thead>
                                    <tr>
                                        <th>技术</th>
                                        <th>方法</th>
                                        <th>状态码</th>
                                        <th>绕过成功</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
        `;
        
        bypasses.forEach(bypass => {
            html += `
                <tr class="${bypass.bypassed ? 'table-success' : ''}">
                    <td><span class="badge bg-info">${bypass.technique}</span></td>
                    <td>${bypass.method}</td>
                    <td><span class="badge ${getStatusBadgeClass(bypass.status_code)}">${bypass.status_code}</span></td>
                    <td>${bypass.bypassed ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-danger"></i>'}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" 
                                onclick="showBypassDetail('${bypass.technique}', '${bypass.bypassed_payload || ''}', ${bypass.status_code})">
                            <i class="fas fa-eye"></i> 详情
                        </button>
                    </td>
                </tr>
            `;
        });
        
        html += '</tbody></table></div></div></div></div>';
    });
    
    html += '</div>';
    container.innerHTML = html;
}

// 获取状态码徽章样式
function getStatusBadgeClass(statusCode) {
    if (statusCode >= 200 && statusCode < 300) return 'bg-success';
    if (statusCode >= 300 && statusCode < 400) return 'bg-warning';
    if (statusCode >= 400 && statusCode < 500) return 'bg-danger';
    if (statusCode >= 500) return 'bg-dark';
    return 'bg-secondary';
}

// 显示绕过详情
function showBypassDetail(technique, payload, statusCode) {
    const modal = new bootstrap.Modal(document.getElementById('detailModal'));
    const modalBody = document.getElementById('modalBody');
    
    modalBody.innerHTML = `
        <h6>绕过技术: ${technique}</h6>
        <h6>状态码: ${statusCode}</h6>
        <h6>Payload:</h6>
        <pre><code>${payload}</code></pre>
    `;
    
    modal.show();
}

// 加载默认payload
async function loadDefaultPayloads() {
    try {
        const response = await fetch('/api/payloads');
        const payloads = await response.json();
        document.getElementById('payloads').value = payloads.join('\n');
    } catch (error) {
        showAlert('加载默认payload失败: ' + error.message, 'danger');
    }
}

// 显示提示信息
function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.insertBefore(alertDiv, document.body.firstChild);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 导出结果
function exportResults() {
    if (!currentResults) {
        showAlert('暂无检测结果可导出', 'warning');
        return;
    }
    
    const dataStr = JSON.stringify(currentResults, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = `waf-detection-${new Date().toISOString().split('T')[0]}.json`;
    a.click();
    
    URL.revokeObjectURL(url);
    showAlert('结果已导出', 'success');
}

// 复制到剪贴板
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        showAlert('已复制到剪贴板', 'success');
    });
}
